import socket
# 定义函数start_server
def start_server():
    # 创建UDP socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind(('0.0.0.0', 9527)) # 允许外部访问
    print("信令服务器启动 0.0.0.0:9527")

    # 定义MAP
    clients = {}

    while True:
        # 接收客户端的数据
        data, addr = sock.recvfrom(1024)
        client_id = data.decode()

        # 客户端地址
        clients[client_id] = addr
        print(f" {client_id} 注册: {addr}")

        # 启动两个客户端后才互相交互地址
        if len(clients) == 2:
            ids = list(clients.keys())
            print(f"ids {ids} ")
            client1, client2 = ids[0], ids[1]
            print(f"client {client1},{client2} ")
            print(f"clients {clients}")

            # 发送对方地址给客户端
            sock.sendto(f"{client2},{clients[client2][0]},{clients[client2][1]}".encode(), clients[client1])
            sock.sendto(f"{client1},{clients[client1][0]},{clients[client1][1]}".encode(), clients[client2])
            print(f"服务端交换地址成功: {client1} {client2}")

            # 清空等待新连接
            clients.clear()

if __name__ == "__main__":
    start_server()